#include "YTRecorderAmrImpl.h"
#include "YTLog.h"

YTRecorderAmr::YTRecorderAmrImpl::YTRecorderAmrImpl()
	:thRun(osPriorityHigh,DEFAULT_STACK_SIZE),
	nState(REC_STOPPED),
  	nCapacity(640)
{
	
}

YTRecorderAmr::YTRecorderAmrImpl::~YTRecorderAmrImpl()
{

}

void YTRecorderAmr::YTRecorderAmrImpl::Init()
{
	pPlugin = (YTAdapter *)new duer::MediaAdapter();
	thRun.start(this,&YTRecorderAmrImpl::RunRecord);
}

int YTRecorderAmr::YTRecorderAmrImpl::Start()
{
#if 1
	if (nState == REC_STOPPING) 
	{
		while(REC_STOPPED!=nState)
		{
		 	rtos::Thread::wait(100);
		}
	}
	nState = REC_STARTING;
	thRun.signal_set(0x01);
	while(REC_STARTED!=nState)
	{
	 	rtos::Thread::wait(100);
	}
#else
	if (nState == REC_STOPPED) nState = REC_STARTING;
	thRun.signal_set(0x01);
#endif
	YT_LOGI("YTRecorderAmr start");
}

int YTRecorderAmr::YTRecorderAmrImpl::Resume()
{
	
}

int YTRecorderAmr::YTRecorderAmrImpl::Pause()
{

}

int YTRecorderAmr::YTRecorderAmrImpl::Stop()
{
#if 1
	if (nState == REC_STARTING)
	{
		while(REC_STARTED!=nState)
		{
		 	rtos::Thread::wait(100);
		}	
	}
	nState = REC_STOPPING;
	while(REC_STOPPED!=nState)
	{
	 	rtos::Thread::wait(100);
	}
#else
	if (nState > REC_STOPPED)nState = REC_STOPPING;
	while(REC_STOPPED!=nState)
	{
	 	rtos::Thread::wait(100);
	}
#endif
	YT_LOGI("YTRecorderAmr Stop");
}



void YTRecorderAmr::YTRecorderAmrImpl::SetEventListener(IOnEvent* _pEvent)
{
	pEvent = _pEvent;
}


void YTRecorderAmr::YTRecorderAmrImpl::RunRecord()
{
	int rs = 0;
	char *	_rx_buffer = new char [nCapacity];
	while(1)
	{	
		rtos::Thread::signal_wait(0x01);
		YT_LOGI("Entry RunRecord");
	    YT_LOGI("thread: id = %x, used = %d, max = %d", thRun.gettid(), thRun.used_stack(),thRun.max_stack());	
		pPlugin->start_record_amr();
		pEvent ? pEvent->on_start_amr() : 0;
		nState = REC_STARTED;
		while (nState == REC_STARTED) 
		{			
			rs = pPlugin->read_amr(_rx_buffer, nCapacity);
			rs = pEvent ? pEvent->on_data_amr(_rx_buffer, nCapacity) : 0;
		}
	    pPlugin->stop_record_amr();
		YT_LOGI("Leave RunRecord");
	    rs = pEvent ? pEvent->on_stop_amr() : 0;	
	    nState = REC_STOPPED;
	}
	if(_rx_buffer)delete _rx_buffer;
	_rx_buffer = NULL;
}

